package com.example.his.api.mis.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.example.his.api.common.R;
import com.example.his.api.db.pojo.RoleEntity;
import com.example.his.api.mis.controller.form.*;
import com.example.his.api.mis.service.RoleService;
import com.example.his.api.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/mis/role")
@Slf4j
public class RoleController {
    @Resource
    private RoleService roleService;

    @GetMapping("/searchAllRole")
    public R searchAllRole() {
        return R.ok().put("list", roleService.searchAllRole());
    }

    @PostMapping("/searchByPage")
    public R save(@RequestBody @Validated SearchRoleByPageForm form) {
        PageUtils r = roleService.searchByPage(form);
        return R.ok().put("page", r);
    }

    @PostMapping("/insert")
    public R insert(@RequestBody @Validated InsertRoleForm form) {
        int r = roleService.insert(form);
        return R.ok().put("rows", r);
    }



    @PostMapping("/searchById")
    public R searchById(@Valid @RequestBody SearchRoleByIdForm form) {
        HashMap map = roleService.searchById(form.getId());
        return R.ok().put("result",map);
    }

    @PostMapping("/update")
    public R update(@Valid @RequestBody UpdateRoleForm form) {
        RoleEntity role = new RoleEntity();
        role.setId(form.getId());
        role.setRoleName(form.getRoleName());
        role.setPermissions(JSONUtil.parseArray(form.getPermissions()).toString());
        role.setDesc(form.getDesc());
        int rows = roleService.update(role);
        //如果用户修改成功，并且用户修改了该角色的关联权限
        if (rows == 1 && form.getChanged()) {
            //把该角色关联的用户踢下线
            ArrayList<Integer> list = roleService.searchUserIdByRoleId(form.getId());
            list.forEach(userId -> {
                StpUtil.logout(userId);
            });
        }
        return R.ok().put("rows", rows);
    }


    @PostMapping("/deleteByIds")
    public R deleteByIds(@Valid @RequestBody DeleteRoleByIdsForm form) {
        int rows = roleService.deleteByIds(form.getIds());
        return R.ok().put("rows", rows);
    }
}

